import { observable } from 'mobx';
import { observer } from 'mobx-react';
import React, { Component } from 'react';
import { ArrowHelper, PerspectiveCamera, Scene, Vector3, WebGLRenderer } from 'three';
import { CSS3DObject, CSS3DRenderer, CSS3DSprite } from 'three/examples/jsm/renderers/CSS3DRenderer';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

@observer
export default class SwitchScene extends Component
{
    divScene = React.createRef<HTMLDivElement>();
    css3DRenderer = new CSS3DRenderer();
    renderer = new WebGLRenderer();
    scene = new Scene();
    @observable camera = new PerspectiveCamera(
        75,
        this.divScene.current!.offsetWidth / this.divScene.current!.offsetHeight,
        0.1,
        1000
    );
    @observable control = new OrbitControls(this.camera, this.css3DRenderer.domElement || this.renderer.domElement);
    @observable arrowHelperY = new ArrowHelper(new Vector3(0, 1, 0), new Vector3(0, 0, 0), 250, 0x00ff00);
    @observable arrowHelperX = new ArrowHelper(new Vector3(1, 0, 0), new Vector3(0, 0, 0), 250, 0xff0000);
    @observable arrowHelperZ = new ArrowHelper(new Vector3(0, 0, 1), new Vector3(0, 0, 0), 250, 0x0000ff);

    InitThree = () =>
    {
        const { css3DRenderer, divScene, scene, camera, renderer } = this;

        let element = document.createElement('div');
        element.style.backgroundColor = 'rgba(255, 0, 0,0.2)';
        element.style.width = '150px';
        element.style.height = '150px';

        let object = new CSS3DSprite(element);
        object.position.x = 200;
        object.position.y = 0;
        object.position.z = 0;
        object.lookAt(camera.position);
        scene.add(object);

        scene.add(this.arrowHelperY);
        scene.add(this.arrowHelperX);
        scene.add(this.arrowHelperZ);


        camera.position.set(0, 0, 500);
        camera.lookAt(scene.position);

        renderer.setSize(divScene.current!.clientWidth, divScene.current!.clientHeight);
        renderer.domElement.style.position = "absolute";
        divScene.current!.appendChild(renderer.domElement);

        css3DRenderer.setSize(divScene.current!.clientWidth, divScene.current!.clientHeight);
        css3DRenderer.domElement.style.position = "absolute";
        divScene.current!.appendChild(css3DRenderer.domElement);

        this.AnimaLoop();
    };

    AnimaLoop = () =>
    {
        const { scene, camera } = this;
        requestAnimationFrame(this.AnimaLoop);
        this.css3DRenderer.render(scene, camera);
        this.renderer.render(scene, camera);
    };
    componentDidMount()
    {
        this.InitThree();
    }
    render()
    {
        return (
            <div ref={this.divScene} style={{ width: "100%", height: "100%" }} >

            </div>
        );
    }
}
